

//localStorage.setItem('menu', '1');	

// Start when app is launched
function startApp() { 

  getContent('login.html', 'main');
  document.addEventListener("deviceready", onDeviceReady, false);
}


// Get currently loggin in user
function getUser() {
	return localStorage.getItem('id');
}

// General menu loader
function getContent(location, target, callback) {
	/*
	DOJO version 
	dojo.xhrGet({
	    url: location,
	    handleAs: "text",
	    load: function(data){
			dojo.byId(target).innerHTML = data;
	    }
	});
	*/
	
  // JQuery version
  $.ajax({
      url: location,
      dataType: "html",  
      success: function(data){
          $('#' + target).html(data);
          if (callback != null) {  
            callback.call();
          }        
      }
  });
}


function getBarcodeStatic() {
	return '0186660217153'; // Peanut Butter
}


function getBarcodeCamera() {
	return localStorage.getItem('barcode');
}


// Wrapper: either static or recently scanned
function getProductBarcode() {
   return getBarcodeCamera();
   //return getBarcodeStatic();
}

// Wraooer: set product barcode
function setProductBarcode(code) {
	localStorage.setItem('barcode', code);	
}


//----------===========Load General Info on an Item for info.thml and edit html============------------
function loadItemInfo(data){
	// Item was found
	if (data['error'] == 0) {
  	  $('#item_container').empty();	
	  var item = document.createElement("div");
	  var eatable;        
      var txtNode = document.createTextNode(data.name);
      var style;
      eatable=data.eatable;
      if(eatable==1)
      	style='greenish';
      else
      	style='redish';
      $('#info_container').attr('class', style);          
      $(item).append(txtNode);
      $('#item_container').append(item);
	}
	else {
		// Item not found
		var c = confirm("Product not found. Add it now?");
	    if (c == true) {
	    	pname = prompt("Enter product name:");
	    	params = "?name=" + pname;
	    	barcode = data['msg'];
		    var addproduct_url = "http://www.e-fairy.com/products/add/" + barcode + params;
		    $.getJSON(addproduct_url, function(data) {
	    	    loadItemInfo(data);
	        });	    	
	    }	
	    // Passively wait
	    else {
	    	$('#no_products').attr('class', 'important visible');
	    }
	}
}

function loadItemEdit(data){
	  $('#item_container').empty();  
	  var item = document.createElement("div");      
      var txtNode = document.createTextNode(data.name);        
      $(item).append(txtNode);
      $('#item_container').append(item);
}
//----=====================End of Load General Info==================------------------------

// --===Load additives in Info.html===---
function loadAdditives(data) {
		  /*
		   * Updated! Classification:
		   * category = 0. Harmles
		   * category = 1. Questionable
		   * category = 2. Avoidable
		   * category = 3. Banned in some countries
		   */
		  var counter = 0;   
		  $('#additive_container').empty();   
	      $('#additives_loading').attr('class', 'loader invisible');
	      $.each(data, function(index, val) {
		      val['code'] = data[counter].code;

		      if(data[counter].category == 0) {
			      style = 'additive_harmless';
		      }	      
		      else if(data[counter].category == 1) {
			      style = 'additive_questionable';
		      }
		      else if(data[counter].category == 2) {
		          style = 'additive_avoidable';
		      }
		      else if(data[counter].category == 3) {
		          style = 'additive_banned';
		      }
			  var additive = document.createElement("div");
			  additive.setAttribute('class', style);
	            
	          var alink = document.createElement("a");
	          var txtNode = document.createTextNode(val['code']); 
	          alink.setAttribute('href', '#');
	          alink.setAttribute('onClick', "js:getE('" + val['code'] + "');");
	          $(alink).append(txtNode);           
	           
	          $(additive).append(alink);
	          $('#additive_container').append(additive);
		      counter++;
        });    
}
//-----------=============Load Additives in Edit.html===========----------------

function loadAdditivesEdit(data){
		/*
		   * Updated! Classification:
		   * category = 0. Harmles
		   * category = 1. Questionable
		   * category = 2. Avoidable
		   * category = 3. Banned in some countries
		   */
		  var counter = 0;   
		  $('#additive_container').empty();   
	      $('#additives_loading').attr('class', 'loader invisible');
	      $.each(data, function(index, val) {
		      val['code'] = data[counter].code;

		      if(data[counter].category == 0) {
			      style = 'additive_harmless';
		      }	      
		      else if(data[counter].category == 1) {
			      style = 'additive_questionable';
		      }
		      else if(data[counter].category == 2) {
		          style = 'additive_avoidable';
		      }
		      else if(data[counter].category == 3) {
		          style = 'additive_banned';
		      }
			  var additive = document.createElement("div");
			  additive.setAttribute('class', style);
	            
	          var alink = document.createElement("a");
	          var txtNode = document.createTextNode(val['code']);
	          var button=document.createElement('button');
	          var txtNode3 = document.createTextNode('Delete');
	  		  $(button).append(txtNode3);
	          button.setAttribute('onClick', "js:deleteAdditive('" + val['code'] + "');"); 
	          alink.setAttribute('href', '#');
	          alink.setAttribute('onClick', "js:getE('" + val['code'] + "');");
	          $(alink).append(txtNode);           
	          $(additive).append(alink);
	          $(additive).append(button);
	          $('#additive_container').append(additive);      
		      counter++;
        });    
}


// -----------=========Load ingredients in Info.html=========------------
function loadIngredients(data)
{     
	  $('#ingredients_container').empty();
	  $('#ingredients_loading').attr('class', 'loader invisible');   
      $.each(data, function(index, val) {
	    var ingredient = document.createElement("div");
	    var br = document.createElement("br");
	    ingredient.setAttribute('class', 'ingredient');            
        var txtNode = document.createTextNode(val['name']);           
        $(ingredient).append(txtNode);
        $('#ingredients_container').append(ingredient);
          //$('#ingredients_container').append(br);
      });
}

// -----------=========Load ingredients in Edit.html=========------------
function loadIngredientsEdit(data){
	  $('#ingredients_container').empty();   
	  $('#ingredients_loading').attr('class', 'loader invisible');
      $.each(data, function(index, val) {
	    var ingredient = document.createElement("div");
	    var br = document.createElement("br");
	    ingredient.setAttribute('class', 'ingredient');            
        var txtNode = document.createTextNode(val['name']);           
        $(ingredient).append(txtNode);
        
        var button=document.createElement('button');
	    var txtNode3 = document.createTextNode('Delete');
	  	$(button).append(txtNode3);
	    button.setAttribute('onClick', "js:deleteIngredient('" + val['name'] + "');"); 
        $(ingredient).append(button);
        $('#ingredients_container').append(ingredient);
          //$('#ingredients_container').append(br);
      });
}

 // -------------========Load allergens in Info.html=========-------------
function loadAllergens(data){
	 $('#alergens_container').empty();
	 $('#allergens_loading').attr('class', 'loader invisible');         
     $.each(data, function(index, val) {
	    var allergen = document.createElement("div");
	    allergen.setAttribute('class', 'alergens');            
        var txtNode = document.createTextNode(val['name']);           
        $(allergen).append(txtNode);
      	$('#alergens_container').append(allergen);
      });
} 

// -------------========Load allergens in Edit.html=========-------------
function loadAllergensEdit(data){
	  $('#alergens_container').empty();
	  $('#fromBox').empty();
	  $('#allergens_loading').attr('class', 'loader invisible');
	  var first = document.createElement("option");
      first.setAttribute('class', 'alergens');            
	  var txtNode2 = document.createTextNode('Add Alergen');           
	  $(first).append(txtNode2);
	  $('#fromBox').append(first);
	         
      $.each(data, function(index, val) {
	    var allergen = document.createElement("div");
	    allergen.setAttribute('class', 'alergens');            
        var txtNode = document.createTextNode(val['name']);           
        $(allergen).append(txtNode);
        
        var button=document.createElement('button');
	    var txtNode3 = document.createTextNode('Delete');
	  	$(button).append(txtNode3);
	    button.setAttribute('onClick', "js:deleteAlergen('" + val['name'] + "');"); 
        $(allergen).append(button);
        
      	$('#alergens_container').append(allergen);
      });
      addAlergen();
}


//----------===============Adding Information on an Item================----------------
// Called when user edits product and adds its name
function addItemName(){
	var itemname = prompt("Enter Item name", "");
	var barcode = getProductBarcode(); 	  	    	
	var params = "?name=" + itemname;  
	var iteminfo_url = "http://www.e-fairy.com/products/set/" + barcode + params;
	$.getJSON(iteminfo_url, function(data) { 
    	loadItemEdit(data);
    });
}

// Called when user edits product and adds additive
function addAdditive(){
	var additive = prompt("Enter Item additives ex: e443,e321", "");
	var barcode = getProductBarcode(); 	    	
	var params = "?additive=" + additive;
	var additives_url = "http://www.e-fairy.com/additives/add/" + barcode + params;
	$.getJSON(additives_url, function(data) {
    	loadAdditivesEdit(data);
    });
}
// Called when user edits product and adds ingredients
function addIngredient(){
	var ingredient = prompt("Enter Item additives ex: sugar,salt", "");
	var barcode = getProductBarcode(); 	  	    	
	var params = "?ingredient=" + ingredient;  
	var ingredients_url = "http://www.e-fairy.com/ingredients/add/" + barcode + params;
	$.getJSON(ingredients_url, function(data) {
    	loadIngredientsEdit(data);
    }); 
}

// After modification, send selected allergens to server
function sendAllergens() {
	//alert();
	var barcode = getProductBarcode(); 	  	    	
	var params = "?allergen=" + $("#fromBox").val();  
	var allergens_url = "http://www.e-fairy.com/allergens/add/" + barcode + params;
	$.getJSON(allergens_url, function(data) {
	   	loadAllergensEdit(data);
	});
}

// Called when from addAlergens() when user edit product and wnats to add alergens
function loadAllergensOptions(data){
    //$('#fromBox').attr('class','loader_on');
		$.each(data, function(index, val) {	
	    var option = document.createElement("option");
		option.setAttribute('class', 'alergens');            
	    var txtNode = document.createTextNode(val['name']);           
	    $(option).append(txtNode);
	    $(option).attr('value',val['id']);
	    $('#fromBox').append(option);
	});
	//var singleValues = $("#fromBox").val();
}

// Called when user edits product and adds alergens
function addAlergen(){
	var allergens_url = "http://www.e-fairy.com/allergens/options";
	$.getJSON(allergens_url, function(data) { 
    	loadAllergensOptions(data);
    });
}

//-----------=============End of Adding Inforation on an Item==============---------------


//--------------==============Start of Information Deleting on an Item============----------------

function deleteAdditive(data)
{
	var c=confirm("Do you really want to delete "+data+"?");
	if(c==true)
	{
		var barcode = getProductBarcode(); 	    	
		var params = "?additive=" + data;
		var additives_url = "http://www.e-fairy.com/additives/delete/" + barcode + params;
		$.getJSON(additives_url, function(data) {
	    	loadAdditivesEdit(data);
	    });
		}	
	else
	{
		alert("You pressed Cancel!");
	}
}


function deleteIngredient(data){
	var c=confirm("Do you really want to delete "+data+"?");
	if(c==true)
	{
		var barcode = getProductBarcode(); 	    	
		var params = "?ingredient=" + data;
		var additives_url = "http://www.e-fairy.com/ingredients/delete/" + barcode + params;
		$.getJSON(additives_url, function(data) {
	    	loadIngredientsEdit(data);
	    });
		}	
	else
	{
		alert("You pressed Cancel!");
	}
}


function deleteAlergen(data){
	var c=confirm("Do you really want to delete "+data+"?");
	if(c==true)
	{
		var barcode = getProductBarcode(); 	    	
		var params = "?allergen=" + data;
		var allergens_url = "http://www.e-fairy.com/allergens/delete/" + barcode + params;
		$.getJSON(allergens_url, function(data) {
	    	loadAllergensEdit(data);
	    });
		}	
	else
	{
		alert("You pressed Cancel!");
	}
}

//--------------==============End of Information Deleting on an Item============----------------

function loadCommentsFromJSON(data) {
	/* 
	$(function(){
			itemsPerPage = 5;
			paginatorStyle = 2;
			paginatorPosition = 'bottom';
			//enableGoToPage = true;
		$('#ReviewContainer').pagination();
	});
	 */
    
	$('#reviews_loading').attr('class', 'loader invisible');
   	$('#ReviewContainer').empty();   	
   	var myStarifys = new Array(); 
    $.each(data, function(index, val) {
            // Some stuff
            var myReview = document.createElement("div");
			var myAvatar = document.createElement("img");
			var myReviewComment = document.createElement("div");
			
			myReview.setAttribute("class", 'review');
			myReview.setAttribute("id", 'myReview');
			
			
			myAvatar.setAttribute("src",val['avatar']);
			myAvatar.setAttribute("class", 'review_avatar');			
			myReviewComment.setAttribute("class", 'review_comment');
			
			var theTextContent = document.createTextNode(val['content']);
			myReviewComment.appendChild(theTextContent);
			
			var myTrustLevel = document.createElement("span");
			myReviewComment.appendChild(myTrustLevel);
			
						
			// Name element
			var myReviewFooterName = document.createElement("span");
			myReviewFooterName.setAttribute("class", 'review_footer');					
			var theTextFooter = document.createTextNode(val['user']);
			myReviewFooterName.appendChild(theTextFooter);
									
			// Date element
			var theReviewFooterDate = document.createElement("span");
			theReviewFooterDate.setAttribute("class", 'review_date')			
			var myDate = document.createTextNode(val['thedate']);
			theReviewFooterDate.appendChild(myDate);
			
			// Container for name + data
			var myReviewFooter = document.createElement("div");
			myReviewFooter.appendChild(myReviewFooterName);
			myReviewFooter.appendChild(theReviewFooterDate);
			
			
			var myReviewSpacer = document.createElement("br");
			myReviewSpacer.setAttribute("class", 'review_spacer');
			
			myReview.appendChild(myAvatar);
			myReview.appendChild(myReviewComment);
			myReview.appendChild(myReviewFooter);									 
			myReview.appendChild(loadCommentStars(index));
			myReview.appendChild(myReviewSpacer);			
			
			//alert(myReview.innerHTML);
			var sname = "#starify" + index;
			myStarifys.push(sname);

			
			$('#ReviewContainer').append(myReview);
        });        

        $.each(myStarifys, function(index, val) {
        	$(val).stars();
        });
                
}
 /* loading the stars into each comment */
function loadCommentStars(i){
	var myStarify = document.createElement("div");
	
	myStarify.setAttribute("class", 'multifield');
	myStarify.setAttribute("id", 'starify' + i);
	for(x = 0; x < 5; x++){
		var myLabel = document.createElement("label");
		myLabel.setAttribute("for", 'vote'+x);
		myLabel.setAttribute("class", 'blockLabel');
		myLabel.setAttribute("style", 'display: none;');
		
		var myRadioBtn = document.createElement("input");
		myRadioBtn.setAttribute("type", 'radio');
		myRadioBtn.setAttribute("name", 'vote');
		myRadioBtn.setAttribute("id", 'vote'+x);
		myRadioBtn.setAttribute("value", x);
		
		var myLabelText = "";
		if(x==0){
			myLabelText = "Poor";
		}
		else if(x==1){
			myLabelText = "Fair";
		}
		else if(x==2){
			myLabelText = "Average";
		}
		else if(x==3){
			myLabelText = "Good";
		}
		else if(x==4){
			myLabelText = "Excellent";
		}
		
		var theText = document.createTextNode(myLabelText);
		
		myLabel.appendChild(myRadioBtn);
		myLabel.appendChild(theText);

		myStarify.appendChild(myLabel);
	}
	
	return myStarify;	
}

function loadRatingsfromJSON(data){	
   $('#ratings_loading').attr('class', 'loader invisible');   
   $('#myLikesDislikes').empty();

   var myLikesBar = document.createElement("div");
   var myDislikesBar = document.createElement("div");
   var myBr = document.createElement("br");
   	
   var LBarVal = data['likes'];
   var DBarVal = data['dislikes'];
   	
   var LBarPercent = (LBarVal/(LBarVal+DBarVal))*100;
   var DBarPercent = (DBarVal/(LBarVal+DBarVal))*100;
   	
   myLikesBar.setAttribute("style", 'width: '+ (Math.round(LBarPercent)) +'%');
   myLikesBar.setAttribute("class", "bar_green");
   myDislikesBar.setAttribute("style", 'width: '+ (Math.round(DBarPercent)) +'%');
   myDislikesBar.setAttribute("class", "bar_red");
   myBr.setAttribute("style", 'clear: both');
      
   $('#myLikesDislikes').append(myLikesBar);
   $('#myLikesDislikes').append(myDislikesBar);
   $('#myLikesDislikes').append(myBr);
   
   $('#clikes').html(LBarVal);
   $('#cdislikes').html(DBarVal);
   	
   //alert(document.getElementById('myLikesDislikes').innerHTML); 
	
   //Old score stuff  	
   /*	
   var myCurrScore = document.createElement("div");
   myCurrScore.setAttribute("class", 'ratings_score');
        
   var myRatings = document.createTextNode("Score: " + data['score']);
   myCurrScore.appendChild(myRatings);
    
   var ratingsSpacer = document.createElement("br");
   ratingsSpacer.setAttribute("class", 'ratings_spacer');
   myCurrScore.appendChild(ratingsSpacer);
        
   $('#RatingsContainer').append(myCurrScore);   
   */
}
// Called when user presses the Thumbs Up button
function ratingGoUp(){
	var barcode = getProductBarcode(); 	    	
	//var params = "?additive=" + additive;
	var ratings_url = "http://www.e-fairy.com/products/like/" + barcode;
	$('#ratings_loading').attr('class', 'loader visible');
	$.getJSON(ratings_url, function(data) {
    	loadRatingsfromJSON(data);
    });
}

// Called when user presses the Thumbs Down button
function ratingGoDown(){
	var barcode = getProductBarcode(); 	    	
	//var params = "?additive=" + additive;
	var ratings_url = "http://www.e-fairy.com/products/dislike/" + barcode;
	$('#ratings_loading').attr('class', 'loader visible');
	$.getJSON(ratings_url, function(data) {
    	loadRatingsfromJSON(data);
    });
}

// When clicked on "add review" button
function addReview() {
	var review = prompt("Enter your review", ""); // Prompt the text	
	var barcode = getProductBarcode(); 	  	  
	var params = "?user=" + getUser() + "&content=" + review;  		
	var addReviewUrl = "http://www.e-fairy.com/reviews/add/" + barcode + params;
	$('#reviews_loading').attr('class', 'loader visible');	
	$.getJSON(addReviewUrl, function(data) {	// Refresh view according to new data
		loadCommentsFromJSON(data['reviews']);
	});	
}


function loadBoth(data) {	
    loadCommentsFromJSON(data['reviews']);    
    loadRatingsfromJSON(data);  	
}

// Load reviews example
function loadReviewsPanel() {
	$("#starify").stars({
		
	});     

	var reviews_url = "http://www.e-fairy.com/reviews/all/" + getProductBarcode();           
	$('#reviews_loading').attr('class', 'loader visible');
	$('#ratings_loading').attr('class', 'loader visible');
    $.getJSON(reviews_url, function(data) {       	  
        loadBoth(data);	
    });
}

// -----=========Load Info Panel=========------------
function loadInfoPanel(){
	var barcode = getProductBarcode();
    var additives_url = "http://www.e-fairy.com/additives/all/" + barcode;
    var ingredients_url = "http://www.e-fairy.com/ingredients/all/" + barcode;
    var allergens_url = "http://www.e-fairy.com/allergens/all/" + barcode;
    var iteminfo_url ="http://www.e-fairy.com/products/info/" + barcode;
    
    
    $.getJSON(iteminfo_url, function(data) { 
    	loadItemInfo(data);
    });
    
    $('#additives_loading').attr('class', 'loader visible');
    $.getJSON(additives_url, function(data) {
    	loadAdditives(data);
    });
    
    $('#ingredients_loading').attr('class', 'loader visible');
    $.getJSON(ingredients_url, function(data) {
    	loadIngredients(data);
    }); 
    
    $('#allergens_loading').attr('class', 'loader visible');
    $.getJSON(allergens_url, function(data) { 
    	loadAllergens(data);
    });
}

function loadInfoEditPanel(){
	var barcode = getProductBarcode();
    var additives_url = "http://www.e-fairy.com/additives/all/" + barcode;
    var ingredients_url = "http://www.e-fairy.com/ingredients/all/" + barcode;
    var allergens_url = "http://www.e-fairy.com/allergens/all/" + barcode;
    var iteminfo_url ="http://www.e-fairy.com/products/info/" + barcode;
    
    $.getJSON(iteminfo_url, function(data) { 
    	loadItemEdit(data);
    });
    
    $('#additives_loading').attr('class', 'loader visible');
    $.getJSON(additives_url, function(data) {
    	loadAdditivesEdit(data);
    });
    
    $('#ingredients_loading').attr('class', 'loader visible');
    $.getJSON(ingredients_url, function(data) {
    	loadIngredientsEdit(data);
    }); 
    
    $('#allergens_loading').attr('class', 'loader visible');
    $.getJSON(allergens_url, function(data) { 
    	loadAllergensEdit(data);
    });
}

// -------===========Open Info subpanel===============
function getPanelInfo() {
	setMenu('1'); // Adjust menu style	
	getContent('info.html', 'panel', loadInfoPanel); // Load placeholders	
}

// -------===========Open Edit subpanel===============
function getPanelEditInfo(){
	setMenu('1'); // Adjust menu style	
	getContent('edit.html', 'panel', loadInfoEditPanel); // Load placeholders
}

// Open Reviews subpanel
function getPanelReviews() {
	setMenu('2'); // Adjust menu style
	getContent('reviews.html', 'panel', loadReviewsPanel); // Load placeholders
}

// Camera capture stuff

function PictureSourceType() {
	
};

PictureSourceType.PHOTO_LIBRARY = 0;
PictureSourceType.CAMERA = 1;
 
function getPicture(sourceType)
{
  navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50});
};

// Loads picture in container and submits to server
function onPhotoDataSuccess(imageData)
{   
   document.getElementById("test_img").src = "data:image/jpeg;base64," + imageData;
   var feedUrl = "http://www.e-fairy.com/products/picture";   
   $.ajax({ 
   	  type: 'POST',
   	  data: {img: imageData},   	  
      url: feedUrl,
      dataType: "text",        
      success: function(data){
          // Done
      }
   });
}

// When barcode scanning fails
function onFail(message) {
    alert('Failed because: ' + message);
}

// Input item by keyboard
function inputItem() {
	var barcode = prompt("Enter barcode or name", "");	
	setProductBarcode(barcode)
	refreshView(); 
}

// Set one option active (darker tab), others inactive (lighter)
function setMenu(rid) {
	var id = '#menu' + rid;       
	$('#menu1').removeClass('menu_active menu_inactive').addClass('menu_inactive');
	$('#menu2').removeClass('menu_active menu_inactive').addClass('menu_inactive');
	$('#menu3').removeClass('menu_active menu_inactive').addClass('menu_inactive');
	$(id).removeClass('menu_inactive').addClass('menu_active');
	localStorage.setItem('menu', rid);			
}


// Get extra information about additive
function getE(e) {    
	var additiveinfo_url = "http://www.e-fairy.com/additives/info/" + e;
    $.getJSON(additiveinfo_url, function(data) { 
    	alert(data['name']);
    });  
}


function confirmNotFound(button) {
    if ((button + '') == '1') {	
        getContent('add.html', 'panel');
    }
}

function onNotFound() {
	navigator.notification.confirm(
	    "Given item was not found. Do you want to add it?",
	    confirmNotFound,    
	    "Item not found",
	    "Yes,No"
	);
}


// Prepare camera
function onDeviceReady() {
  pictureSource = navigator.camera.PictureSourceType;
  destinationType = navigator.camera.DestinationType;
  
}

function onSuccess(imageData) {
    var image = document.getElementById('myImage');
    image.src = "data:image/jpeg;base64," + imageData;
}

// After scan is sucessful
function onScan() {
    window.plugins.barcodeScanner.scan(BarcodeScanner.Type.ONE_D_CODE_TYPES, //EAN_13,
       function(result) {
       	 //alert("Got barcode: " + result);
       	 setProductBarcode(result);
       	 // Reload current panel
       	 refreshView();	     
       },
       function(error) {
	       alert("Scanning failed: " + error);
	   }, 
	   {yesString: "Install"}
    );
}

// Password reminder feature
function remindPassword() {
  var username = $('#name').val();
  if (username == "") {
	alert("Enter username")
  }	
  else {
  	var passRemindUrl = "http://www.e-fairy.com/person/remind/" + username;
    $.getJSON(passRemindUrl, function(data) {
        alert(data['msg']);  	
    });
  }
}


// Actually do login
function doLogin(name, password, remember) {
	// Save session?
	if (remember == true) {
		localStorage.setItem('user', name);
		localStorage.setItem('pass', password);
		localStorage.setItem('remember', '1');
  	}
  	else {
		localStorage.setItem('user', '');
		localStorage.setItem('pass', '');
		localStorage.setItem('remember', '0');  			
  	}	
  	// Load interactive view
  	getContent('interactive.html', 'main');	
}

// Tries to authentificate, if ok, set session vars and redirect
function getLogin() {
  var name = $('#name').val();
  var password = $('#password').val();
  var params = "?name=" + name + "&pass=" + password;
  var fullLoginUrl = "http://www.e-fairy.com/person/login" + params;
  
  $.getJSON(fullLoginUrl, function(data) {
    if (data['error'] == 0) {	    		
		localStorage.setItem('username', name);
		localStorage.setItem('id', data['id']);			   
		doLogin(name, password, $('#remember:checked').val() !== undefined);
	}
	else {
		alert(data['msg']);					
		//navigator.camera.getPicture(onSuccess, onFail, { quality: 50 }); 		 		
	}	
  });    
}

function signup() {
    var name = $('#name').val();
    var password1 = $('#password').val();
    var password2 = $('#password2').val();
    var email = $('#email').val();
    if (password1 != password2) {
    	alert("Passwords differ");
    }
    else if (name == '') {
    	alert("Enter username");
    }    
    else if (password1 == '') {
    	alert("Enter password");
    } 
    else {
    	// check in server side
    	var params = "?name=" + name + "&pass=" + password + "&email=" + email;
    	var fullSignupUrl = "http://www.e-fairy.com/person/signup" + params;	
        $.getJSON(fullSignupUrl, function(data) {
           if (data['error'] == 0) {          
			   // Do not remember by default
               doLogin(name, password, false);
           }
           else {
               alert(data['msg']);
           }
        });
    }
		
}


// Call when other product is entered
function refreshView() {
	menu = localStorage.getItem('menu');
	if (menu == '2') {
		getPanelReviews();
	}
	else if (menu == '1') {
		getPanelInfo();
	}
	else { // Default panel
		getPanelInfo();
	}
}


